package com.bei.lingluan.utils;

import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.Image;
import ohos.media.image.common.ImageFormat;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

/**
 *
 *
 * @author 北海
 *
 */
public class HttpUtils {

    /**
     * 用于向指定网址发送和接收数据
     * @param context      上下文
     * @param urlString    请求的地址
     * @param method       get或post请求方式
     * @param data         请求方式为post时，通过请求体传递的数据
     * @return             json格式的字符串
     */
    private static String sendRequest(Context context, String urlString, String method, String data) {

        String result = null;

        NetManager netManager = NetManager.getInstance(context);
        if (!netManager.hasDefaultNet()) {
            return null;
        }
        NetHandle netHandle = netManager.getDefaultNet();

        //设置网络变化时的回调函数
        NetStatusCallback callback = new NetStatusCallback() {
            // 重写需要获取的网络状态变化的override函数
        };
        netManager.addDefaultNetStatusCallback(callback);

        HttpURLConnection httpUrlConnection = null;
        try {
            URL url = new URL(urlString);
            //获取连接
            httpUrlConnection = (HttpURLConnection) netHandle.openConnection(url, Proxy.NO_PROXY);
            //设置请求方式
            httpUrlConnection.setRequestMethod(method);

            if(data != null ) {
                //允许通过此网络连接向服务端写数据
                httpUrlConnection.setDoOutput(true);
                httpUrlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

                byte[] bytes = data.getBytes("UTF-8");
                OutputStream os = httpUrlConnection.getOutputStream();
                os.write(bytes);
                os.flush();
            }

            //发送请求建立连接
            httpUrlConnection.connect();

            //读取返回的数据
            if(httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStream is = httpUrlConnection.getInputStream();
                StringBuilder builder = new StringBuilder();
                byte[] bs = new byte[1024];
                int len = -1;
                while((len = is.read(bs))!=-1){
                    builder.append( new String(bs,0,len));
                }
                result = builder.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (httpUrlConnection != null){
                httpUrlConnection.disconnect();
            }
        }
        return result;
    }

    public static String sendImage(Context context, String urlString, Image myImage) {

        String result = null;

        NetManager netManager = NetManager.getInstance(context);
        if (!netManager.hasDefaultNet()) {
            return null;
        }
        NetHandle netHandle = netManager.getDefaultNet();

        //设置网络变化时的回调函数
        NetStatusCallback callback = new NetStatusCallback() {
            // 重写需要获取的网络状态变化的override函数
        };
        netManager.addDefaultNetStatusCallback(callback);

        Image.Component component = myImage.getComponent(ImageFormat.ComponentType.JPEG);
        byte[] bytes = new byte[component.remaining()];
        component.read(bytes);

        HttpURLConnection httpUrlConnection = null;
        try {
            URL url = new URL(urlString);
            //获取连接
            httpUrlConnection = (HttpURLConnection) netHandle.openConnection(url, Proxy.NO_PROXY);
            //设置请求方式
            httpUrlConnection.setRequestMethod("POST");

            //允许通过此网络连接向服务端写数据 multipart/form-data
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setRequestProperty("Content-Type", "image/jpeg");

            OutputStream os = httpUrlConnection.getOutputStream();
            os.write(bytes);
            os.flush();

            //发送请求建立连接
            httpUrlConnection.connect();
            System.out.println(httpUrlConnection.getResponseCode());

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (httpUrlConnection != null){
                httpUrlConnection.disconnect();
            }
        }
        return result;
    }

    public static String sendGetRequest(Context context, String urlString){
        return sendRequest(context,urlString,"GET",null);
    }
    public static String sendPostRequest(Context context,String urlString,String data){
        return sendRequest(context,urlString,"POST",data);
    }


}
